﻿#include "FormContact.h"
#include "DialogContact.h"
#include "MainFrm.h"

#include <QtXml>
#include <QtGui>
#include <QtNetwork>

const QString FormContact::m_strRoot = "./data/ContactList.xml";
FormContact::FormContact(QWidget * parent, Qt::WFlags f): SubFrame(parent, f)
{
	m_strCurIndex = "";
	QVBoxLayout* layoutTop = new QVBoxLayout(this);

	m_treeWidget = new QTreeWidget(this);

	connect( m_treeWidget,
			 SIGNAL( itemDoubleClicked ( QTreeWidgetItem * , int )), 
			 this, 
			 SLOT( itemDbClicked(QTreeWidgetItem*, int ) ) ) ;

	connect( m_treeWidget,
			 SIGNAL( itemClicked ( QTreeWidgetItem * , int )), 
			 this, 
			 SLOT( itemClicked(QTreeWidgetItem*, int ) ) ) ;

	layoutTop->addWidget(m_treeWidget);
	//
	QStringList headerLabels;
    headerLabels << tr("姓名")<< tr("手机")<< tr("E-MAIL");
	m_treeWidget->setHeaderLabels(headerLabels);

	m_treeWidget->header()->setSortIndicator(2, Qt::AscendingOrder);
	m_treeWidget->header()->setSortIndicatorShown(true);
	m_treeWidget->header()->setClickable(true);

	refresh();

	m_menuPop = new QMenu(this);
	QAction *act = m_menuPop->addAction(QIcon("./images/filenew.png"),tr("Add"));
	connect(act, SIGNAL(triggered()), this, SLOT(createContact()));
	act = m_menuPop->addAction(QIcon("./images/filesave.png"),tr("Modify"));
	connect(act, SIGNAL(triggered()), this, SLOT(saveContact()));
	act = m_menuPop->addAction(QIcon("./images/delete.png"),tr("Delete"));
	connect(act, SIGNAL(triggered()), this, SLOT(deleteContact()));

	connect( m_treeWidget,
			 SIGNAL( customContextMenuRequested (const QPoint &)), 
			 this, 
			 SLOT( showTreeMenu(const QPoint & ) ) );
	m_treeWidget->setContextMenuPolicy ( Qt::CustomContextMenu);
}

FormContact::~FormContact(void)
{

}
void FormContact::showTreeMenu(const QPoint & pos)
{
	QPoint pg = m_treeWidget->mapToGlobal(pos);
	pg.setY(pg.y() + 20);
	m_menuPop->exec(pg);
}
void FormContact::fileNew(void)
{
	createContact();
}
void FormContact::createContact(void)
{
	DialogContact dlg("New Contact", this);
	if(QDialog::Accepted == dlg.exec())
	{
		QDate date(QDate::currentDate());
		QString str = date.toString(Qt::ISODate);
		QTime time(QTime::currentTime());
		str += " " + time.toString(Qt::ISODate);
		createContact(str,dlg);
		refresh();
	}
}
void FormContact::saveContact(void)
{
	DialogContact dlg("Mody Contact", this);
	if(QDialog::Accepted == showContact(m_strCurIndex,dlg))
	{
		saveContact(m_strCurIndex,dlg);
		refresh();
	}
}
void FormContact::deleteContact(void)
{
	deleteContact(m_strCurIndex);
	refresh();
}

void FormContact::itemClicked(QTreeWidgetItem* item, int column)
{
	m_strCurIndex = item->data(0,Qt::UserRole).toString();
}

void FormContact::itemDbClicked(QTreeWidgetItem* item, int column)
{
	DialogContact dlg("View Contact", this);
	showContact(item->data(0,Qt::UserRole).toString(),dlg);
}

void FormContact::refresh(void)
{
	m_treeWidget->clear();
    QFile contactfile(FormContact::m_strRoot);
    QDomDocument document;
    document.setContent(&contactfile);
    QDomElement documentElement = document.documentElement();
    QDomNodeList categoryNodes = documentElement.elementsByTagName(tr("contact"));

	for (int i = 0; i < int(categoryNodes.length()); ++i)
	{
        QDomNode categoryNode = categoryNodes.item(i);
		QTreeWidgetItem *it = new QTreeWidgetItem(m_treeWidget);
		QDomElement element = categoryNode.toElement();
		QString name = element.attribute(tr("name"));
		it->setText(0, name);
		it->setText(1, element.attribute(tr("mobile")));
		it->setText(2, element.attribute(tr("email")));
		it->setIcon(0,QIcon("./images/contact.png"));	
		it->setData(0, Qt::UserRole, element.attribute(tr("index")));
	}

	contactfile.close();

	return;

	if (!contactfile.open(QIODevice::WriteOnly))
	{
		return; // handle error
	}
	QTextStream out(&contactfile);
	document.save(out, 10);
	contactfile.close();
}


int FormContact::showContact(const QString& index, DialogContact& dlg)
{
    QFile contactFile(FormContact::m_strRoot);
    QDomDocument document;
    document.setContent(&contactFile);
	contactFile.close();
    QDomElement documentElement = document.documentElement(); 

	if ( documentElement.isElement() && documentElement.nodeName() == tr("contactlist") )
	{
		QDomNode node;
		node = documentElement.firstChild();
		while ( !node.isNull() )
		{
			QDomElement elem = node.toElement();
			if(elem.attribute("index") == index)
			{
				dlg.m_editName->setText(elem.attribute(tr("name")));
				dlg.m_editMobile->setText(elem.attribute(tr("mobile")));
				dlg.m_editEmail->setText(elem.attribute(tr("email")));
				dlg.m_editComment->setPlainText(elem.attribute(tr("comment")));
				return dlg.exec();
			}
			node = node.nextSibling();
		}
	}

	return -1;

}
int FormContact::saveDom(QDomElement& elem, DialogContact& dlg)
{
	elem.setAttribute( tr("name"), dlg.m_editName->text());
	elem.setAttribute( tr("mobile"), dlg.m_editMobile->text());
	elem.setAttribute( tr("email"), dlg.m_editEmail->text());
	elem.setAttribute( tr("comment"), dlg.m_editComment->toPlainText());
	return 0;
}
int FormContact::saveContact(const QString& index, DialogContact& dlg)
{
    QFile contactFile(FormContact::m_strRoot);
    QDomDocument document;
    document.setContent(&contactFile);
	contactFile.close();
    QDomElement documentElement = document.documentElement(); 

	if ( documentElement.isElement() && documentElement.nodeName() == tr("contactlist") )
	{
			QDomNode node;
			node = documentElement.firstChild();
			while ( !node.isNull() )
			{
				QDomElement elem = node.toElement();
				if(elem.attribute(tr("index")) == index)
				{
					saveDom(elem, dlg);

					if (!contactFile.open(QIODevice::WriteOnly))
					{
						return -1; // handle error
					}
					QTextStream out(&contactFile);
					document.save(out, 10);
					contactFile.close();

					return 0;

				}
				node = node.nextSibling();
			}
	}

	return -1;

}
int FormContact::createContact(const QString& index, DialogContact& dlg)
{
    QFile contactFile(FormContact::m_strRoot);
    QDomDocument document;
    document.setContent(&contactFile);
	contactFile.close();
    QDomElement documentElement = document.documentElement(); 

	if ( documentElement.isElement() && documentElement.nodeName() == tr("contactlist") )
	{
		QDomElement elem = document.createElement( tr("contact") );
		elem.setAttribute( tr("index"), index);
		saveDom(elem, dlg);
		documentElement.appendChild( elem );

		if (!contactFile.open(QIODevice::WriteOnly))
		{
			return -1; // handle error
		}
		QTextStream out(&contactFile);
		document.save(out, 10);
		contactFile.close();

		return 0;
	}

	return -1;

}

void FormContact::deleteContact(QString& index)
{
    QFile contactFile(FormContact::m_strRoot);
    QDomDocument document;
    document.setContent(&contactFile);
	contactFile.close();
    QDomElement documentElement = document.documentElement(); 

	if ( documentElement.isElement() && documentElement.nodeName() == tr("contactlist") )
	{
			QDomNode node;
			node = documentElement.firstChild();
			while ( !node.isNull() )
			{
				QDomElement elem = node.toElement();
				if(elem.attribute(tr("index")) == index)
				{
					if(QMessageBox::question(this, tr("hello"),
						tr("Really Delete Contact %1?").arg(elem.attribute(tr("name"))),
								 QMessageBox::Yes,
								 QMessageBox::No) == QMessageBox::No)
					{
						return;
					}
					documentElement.removeChild(node);

					if (!contactFile.open(QIODevice::WriteOnly))
					{
						return; // handle error
					}
					QTextStream out(&contactFile);
					document.save(out, 10);
					contactFile.close();

					return;

				}
				node = node.nextSibling();
			}
	}

	return;
}

void FormContact::active()
{
//	MainFrame* pFrame = (MainFrame*)(parent()->parent());
//	pFrame->menuBar()->setHidden(false);
}
